package com.hedl.practice.diyJava.network_programming.TCP_programming;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket sock = new Socket("localhost",6666);     //指定主机上的指定端口号。
        try(InputStream input = sock.getInputStream()){
            try(OutputStream output = sock.getOutputStream()){
                handle(input,output);
            }
        }
        sock.close();
        System.out.println("disconnected.");
    }

    private static void handle(InputStream input, OutputStream output) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(System.in);
        System.out.println("[server] "+reader.readLine());
        for (;;){
            System.out.print(">>> ");       //打印提示
            String s = scanner.nextLine();      //读取一行，使此扫描器前进超过当前行并返回跳过的输入
            writer.write(s);        //写入字符
            writer.newLine();       //写一个行分隔符
            writer.flush();
            String resp = reader.readLine();    //读一行
            System.out.println("<<< "+resp);        //打印
            if (resp.equals("bye")){
                break;
            }
        }
    }
}
